package com.ruoyi.archive.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.archive.domain.*;
import com.ruoyi.archive.mapper.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.validation.Validator;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.archive.service.IArchiveRoomService;

/**
 * 房屋信息Service业务层处理
 *
 * @author yepanpan
 * @date 2025-04-17
 */
@Service
public class ArchiveRoomServiceImpl implements IArchiveRoomService
{
    private static final Logger log = LoggerFactory.getLogger(ArchiveRoomServiceImpl.class);

    @Autowired
    private ArchiveRoomMapper archiveRoomMapper;
    @Autowired
    private ArchiveBuildingMapper archiveBuildingMapper;
    @Autowired
    private ArchivePersonMapper archivePersonMapper;
    @Autowired
    private ArchiveShapeMapper archiveShapeMapper;
    @Autowired
    private ArchiveRoomHistoryMapper archiveRoomHistoryMapper;

    @Autowired
    protected Validator validator;
    /**
     * 查询房屋信息
     *
     * @param id 房屋信息主键
     * @return 房屋信息
     */
    @Override
    public ArchiveRoom selectArchiveRoomById(Long id)
    {
        return archiveRoomMapper.selectArchiveRoomById(id);
    }

    /**
     * 查询房屋信息列表
     *
     * @param archiveRoom 房屋信息
     * @return 房屋信息
     */
    @Override
    public List<ArchiveRoom> selectArchiveRoomList(ArchiveRoom archiveRoom)
    {
        return archiveRoomMapper.selectArchiveRoomList(archiveRoom);
    }

    /**
     * 新增房屋信息
     *
     * @param archiveRoom 房屋信息
     * @return 结果
     */
    @Override
    public int insertArchiveRoom(ArchiveRoom archiveRoom)
    {
        ArchiveRoom old = archiveRoomMapper.selectArchiveRoomByName(archiveRoom.getBuildingId(), archiveRoom.getUnitNum(),  archiveRoom.getName());
        if(old != null){
            throw new ServiceException("房屋已存在:"+old.getName());
        }
        if(archiveRoom.getDeptId() == null){
            ArchiveBuilding archiveBuilding = archiveBuildingMapper.selectArchiveBuildingById(archiveRoom.getBuildingId());
            archiveRoom.setDeptId(archiveBuilding.getDeptId());
        }
        archiveRoom.setCreateTime(DateUtils.getNowDate());
        return archiveRoomMapper.insertArchiveRoom(archiveRoom);
    }

    /**
     * 修改房屋信息
     *
     * @param archiveRoom 房屋信息
     * @return 结果
     */
    @Override
    public int updateArchiveRoom(ArchiveRoom archiveRoom)
    {
        ArchiveRoom old = archiveRoomMapper.selectArchiveRoomByName(archiveRoom.getBuildingId(), archiveRoom.getUnitNum(), archiveRoom.getName());
        if(old != null && !old.getId().equals(archiveRoom.getId())){
            throw new ServiceException("房屋已存在:"+old.getName());
        }
        if(archiveRoom.getUpdateBy() == null){
            archiveRoom.setUpdateBy(SecurityUtils.getUsername());
        }
        archiveRoom.setUpdateTime(DateUtils.getNowDate());

        //记录变更
        if(old == null){
            old = archiveRoomMapper.selectArchiveRoomById(archiveRoom.getId());
        }
        ArchiveRoomHistory history = new ArchiveRoomHistory();
        BeanUtils.copyBeanProp(history, old);
        history.setRoomId(old.getId());
        history.setId(null);
        history.setCreateBy(old.getUpdateBy());
        history.setCreateTime(old.getUpdateTime());
        if(history.getCreateBy() == null){
            history.setCreateBy(archiveRoom.getUpdateBy());
            history.setCreateTime(archiveRoom.getUpdateTime());
        }
        archiveRoomHistoryMapper.insertArchiveRoomHistory(history);

        return archiveRoomMapper.updateArchiveRoom(archiveRoom);
    }

    /**
     * 批量删除房屋信息
     *
     * @param ids 需要删除的房屋信息主键
     * @return 结果
     */
    @Override
    public int deleteArchiveRoomByIds(Long[] ids)
    {
        return archiveRoomMapper.deleteArchiveRoomByIds(ids);
    }

    /**
     * 删除房屋信息信息
     *
     * @param id 房屋信息主键
     * @return 结果
     */
    @Override
    public int deleteArchiveRoomById(Long id)
    {
        return archiveRoomMapper.deleteArchiveRoomById(id);
    }

    /**
     * 导入数据
     *
     * @param dataList 数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importData(List<ArchiveRoom> dataList, Boolean isUpdateSupport, String operName){
        if (StringUtils.isNull(dataList) || dataList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;

        Map<String, ArchiveBuilding> buildingMap  = new HashMap<>();
        List<ArchiveBuilding> buildingList = archiveBuildingMapper.selectArchiveBuildingList(new ArchiveBuilding());
        if(buildingList == null || buildingList.isEmpty()){
            throw new ServiceException("请先添加楼栋信息");
        }
        for(ArchiveBuilding building:buildingList){
            buildingMap.put(building.getDeptName()+"_"+building.getName(), building);
        }

        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (ArchiveRoom row : dataList)
        {
            try
            {
                ArchiveBuilding archiveBuilding = buildingMap.get(row.getDeptName()+"_"+row.getBuildingName());
                if(archiveBuilding == null){
                    throw new ServiceException("楼栋不存在:"+row.getDeptName() + " " + row.getBuildingName());
                }
                row.setDeptId(archiveBuilding.getDeptId());
                row.setBuildingId(archiveBuilding.getId());

                if(StringUtils.isNotEmpty(row.getPersonCard())) {
                    ArchivePerson archivePerson = archivePersonMapper.selectArchivePersonByCard(row.getPersonCard());
                    if(archivePerson == null){
                        throw new ServiceException("户主不存在，请先添加户主信息:"+row.getPersonCard());
                    }
                    row.setPersonId(archivePerson.getId());
                }

                if(StringUtils.isNotEmpty(row.getShapeCode())) {
                    ArchiveShape archiveShape = archiveShapeMapper.selectArchiveShapeByCode(row.getShapeCode());
                    if(archiveShape == null || !archiveShape.getDeptId().equals(row.getDeptId())){
                        throw new ServiceException("户型不存在:"+row.getShapeCode());
                    }
                    row.setShapeId(archiveShape.getId());
                }

                BeanValidators.validateWithException(validator, row);

                // 验证是否存在旧数据
                ArchiveRoom old = archiveRoomMapper.selectArchiveRoomByName(row.getBuildingId(), row.getUnitNum(), row.getName());
                if (StringUtils.isNull(old))
                {
                    row.setCreateBy(operName);
                    insertArchiveRoom(row);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、房屋 " + row.getName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    row.setUpdateBy(operName);
                    row.setId(old.getId());
                    updateArchiveRoom(row);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、房屋 " + row.getName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、房屋 " + row.getName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、房屋 " + row.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
